package adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.text.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.Map;
import app.MyApplication;
import entity.Account;
import entity.HomeZhuYe;
import util.AgentIp;
import util.BitmapUtil;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.JumpActivityUtils;
import util.LogUtil;
import util.NetWorkstateUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import view.diaLogView.EntryPromptDialog;
import view.diaLogView.RetunDialog;
import view.diaLogView.UploadDialog;

/**
 * Created by Administrator on 2016/5/29.
 * 首页的中间视图的适配器
 *
 *   '{"url":' + '"' + "http://172.16.30.214:8080/proxyservice/TransferServlet" + '"' + url":' + '"' + "http://172.16.30.214:8080/proxyservice/TransferServlet" + '"'+'}'
 */
public class RecyclerHome extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener{
    private List<HomeZhuYe.FeatureModelsBean> mListDiddle;
    private List<HomeZhuYe.AdModelsBean> mListAdModels;
    private List<Account.AreaInfoBean> mAreaInfoBeen;
    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private UploadDialog mUploadDialog;
    private Logger mLogger = Logger.getLogger(RecyclerHome.class);
    private DisplayImageOptions mDisplayImageOptions;
    private OnRecyclerViewItemClickListener mOnItemClickListener = null;
    private int mPosition,mChoice; //mChoice 用于区分是什么布局，1代表首页中间需要的视图，2代表首页底部需要的视图
    public RecyclerHome(Context context,List<HomeZhuYe.FeatureModelsBean> middle,List<HomeZhuYe.AdModelsBean> listAdModels,List<Account.AreaInfoBean> areaInfoBeen,int choice){
        this.mContext = context;
        this.mChoice = choice;
        this.mListDiddle = middle;
        this.mListAdModels = listAdModels;
        this.mAreaInfoBeen = areaInfoBeen;

        mLayoutInflater = LayoutInflater.from(mContext.getApplicationContext());
        mDisplayImageOptions = HomeUtil.getHemeUtilNew().getDisplayImageOptions(true,R.mipmap.homepage_icon);
    }

    @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        RecyclerView.ViewHolder holder = null;
        switch (mChoice){
            case 1:
                view = mLayoutInflater.inflate(R.layout.home_item_recycler, parent, false);
                holder = new CustomHolder(mContext,view);
                view.setOnClickListener(this);
                break;
            case 2:
                view = mLayoutInflater.inflate(R.layout.adapter_home_bottoniv, parent, false);
                holder = new HomeBottonIV(mContext,view);
                view.setOnClickListener(this);
                break;
            case 4:
                view = mLayoutInflater.inflate(R.layout.account_adapter, parent, false);
                holder = new AccountText(mContext,view);
                view.setOnClickListener(this);
                break;
            case 3:
                view = mLayoutInflater.inflate(R.layout.adapter_welfare_models_rv, parent, false);
                holder = new CustomHolder(mContext,view);
                view.setOnClickListener(this);
                break;

        }
        return holder;
    }

    @Override public void onBindViewHolder(RecyclerView.ViewHolder holder,int position) {
      if(holder instanceof CustomHolder){
          if(mListDiddle.size() >0  && mListDiddle !=null){
              ((CustomHolder)holder).mTVString.setText(mListDiddle.get(position).getText());
              BitmapUtil.newBitmap().showBitmap(mContext,mListDiddle.get(position).getPic(),((CustomHolder) holder).mIvImage,R.mipmap.homepage_icon,mDisplayImageOptions);
              //将数据保存在itemView的Tag中，以便点击时进行获取
              holder.itemView.setTag(position);
              mPosition = position;
          }

      }else if(holder instanceof HomeBottonIV){
          if(mListAdModels !=null && mListAdModels.size()>0){
              BitmapUtil.newBitmap().showBitmap(mContext,mListAdModels.get(position).getPic(),((HomeBottonIV)holder).mIvImage,R.mipmap.homepage_icon,mDisplayImageOptions);
              holder.itemView.setTag(position);
              mPosition = position;
          }
      }else if(holder instanceof AccountText){
          if(mAreaInfoBeen !=null && mAreaInfoBeen.size()>0){
              ((AccountText)holder).mTextView.setText(mAreaInfoBeen.get(position).getAreaName());
              BitmapUtil.newBitmap().showBitmap(mContext,mAreaInfoBeen.get(position).getAreaPic(),((AccountText)holder).mIvImage,R.mipmap.homepage_icon,mDisplayImageOptions);
              holder.itemView.setTag(position);
              mPosition = position;
          }
      }
    }

    @Override public int getItemCount() {
        if(mChoice == 1){
            return mListDiddle.size();
        }else if(mChoice == 2){
            return mListAdModels.size();
        }else if(mChoice == 3){
             return mListDiddle.size();
        }else if(mChoice == 4){
            return mAreaInfoBeen.size();
        }
        return mChoice;
    }

    @Override public void onClick(View v) {

        int teg = (int) v.getTag();
        if(mChoice == 1){onClick1(teg);
        }else if(mChoice == 2){onClick2(teg);
        }else if(mChoice == 3){
            onClick3(teg);
        }else if(mChoice == 4){
            if(mOnItemClickListener !=null){mOnItemClickListener.onItemClick(teg,"");}
        }
    }

    private static class CustomHolder extends RecyclerView.ViewHolder{
        TextView mTVString;  //展示的字符串
        ImageView mIvImage; //展示的图片

        private CustomHolder(Context context,View view) {
            super(view);

            mTVString = (TextView)view.findViewById(R.id.text_home_recycler);
            mIvImage = (ImageView)view.findViewById(R.id.image_home_recycler);
      /*      WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            int width = (wm.getDefaultDisplay().getWidth())/3;
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.MATCH_PARENT);
            mRelativeLayout.setLayoutParams(layoutParams);*/
        }
    }

    private static class HomeBottonIV extends RecyclerView.ViewHolder {
        ImageView mIvImage; //展示的图片

        private HomeBottonIV(Context context, View view) {
            super(view);
            mIvImage = (ImageView) view.findViewById(R.id.iamge_homebotton_imageview);
        }
    }

    private static class AccountText extends RecyclerView.ViewHolder {
        ImageView mIvImage; //展示的图片
        TextView mTextView;

        private AccountText(Context context, View view) {
            super(view);
            mIvImage = (ImageView) view.findViewById(R.id.image_account_adapter);
            mTextView = (TextView) view.findViewById(R.id.text_account_adapter);
        }
    }

    /**
     * 目前是上网接口的回掉
     * 定义接口 用于itme  的回调
     */
    public interface OnRecyclerViewItemClickListener {
        void onItemClick(int position,String type);
    }
    public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    /**
     * 更新某个item
     */
    public void getChanged(int position,HomeZhuYe.FeatureModelsBean featureModelsBean){
        mListDiddle.set(position,featureModelsBean);
        notifyItemChanged(position);
    }

    /**
     * mChoice 1 的事件
     */
    private void onClick1(int teg){
        if(mListDiddle.get(teg).getType().equals("shipinjiankong")){
            JumpActivityUtils.getInstance().jumpVideoMonitor(mContext);

        } else if(mListDiddle.get(teg).getType().equals("shangwang")){
            mLogger.info("onClick1()....上网按钮被点击");
                if(MyApplication.getApp().getSiteAreaid() == 1){

                    if(mListDiddle.get(teg).getText().equals("断网")){
                        onBrokenNetwork();
                    }else {
                        getJudge();
                    }
                }else if(MyApplication.getApp().getSiteAreaid() == 2){
                    if(mListDiddle.get(teg).getText().equals("断网")){
                        onBrokenNetwork();
                    }else {
                        mOnItemClickListener.onItemClick(teg,mListDiddle.get(teg).getType());
                    }
                }

        }else {
            JumpActivityUtils.getInstance().jumpWebshipoView(mContext, mListDiddle.get(teg).getUrl(), mListDiddle.get(teg).getText());
        }
    }

    /**
     * mChoice 2 的事件
     */
    private void onClick2(int teg){
        JumpActivityUtils.getInstance().jumpWebshipoView(mContext, mListAdModels.get(teg).getUrl(), mListAdModels.get(teg).getText());
    }

    /**
     * mChoice 3 的事件
     */
    private void onClick3(int teg){
        mOnItemClickListener.onItemClick(teg,"");
    }

    /**
     * 断网
     */
    private void onBrokenNetwork(){
        final UploadDialog uploadDialog = new UploadDialog(mContext,"断网中");
        uploadDialog.show();
        NetWorkstateUtil.getInstance().getBrokenNetwork(mContext, new HomeUtil.OnHomeUtilClickListener() {
            @Override
            public void onItemClick(String type) {
                if(type.equals("ok")){
                    final RetunDialog retunDialog = new RetunDialog(mContext,"",7,true);
                    retunDialog.show();
                    uploadDialog.dismiss();
                    HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                        @Override public void run() {
                            retunDialog.dismiss();
                            EventBus.getDefault().post("断网成功");
                        }
                    },1000);
                }else {
                    AgentIp.newInstance(mContext).setNetWorkstate2(new AgentIp.OnNetworkStateClickListener() {
                        @Override
                        public void onClick(boolean state) {
                            uploadDialog.dismiss();
                            if(state){
                                Toast.makeText(mContext,"断网失败",Toast.LENGTH_SHORT).show();
                            }else {
                                final RetunDialog retunDialog = new RetunDialog(mContext,"",7,true);
                                retunDialog.show();
                                HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                                    @Override public void run() {
                                        retunDialog.dismiss();
                                        EventBus.getDefault().post("断网成功");
                                    }
                                },1000);
                            }
                        }
                    });
                }
            }
        },0);
    }

    /**
     *用域名连是否可以连通
     */
    private void getJudge(){
        if(mUploadDialog == null){
            mUploadDialog = new UploadDialog(mContext,"连接中");
            mUploadDialog.show();
        }else {
            mUploadDialog.getStringShow("连接中");
            mUploadDialog.show();
        }
        String stringJson ="{}"; //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,"null","0",time);
        Map map = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,"null","0",Url.mStirngVersion_isAlive,stirngSign,time);
        LogUtil.eE("",StringUtil.getStringUtilNew().getTimeInstance());
        mLogger.info("深大联网...判断网络是否可用--->stringJson--"+stringJson+"fwq"+MyApplication.mFWQIP);
        GreenTreeNetworkUtil.getInstance().doPost(mContext,MyApplication.mFWQIP,500,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    mLogger.info("判断网络是否可用--->String--"+response);
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 1) {
                        mUploadDialog.dismiss();
                        final RetunDialog retunDialog = new RetunDialog(mContext,"",5,true);
                        retunDialog.show();
                        HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                            @Override public void run() {
                                retunDialog.dismiss();
                            }
                        },1000);
                    }

                } catch (JSONException e) {
                    mUploadDialog.dismiss();
                    EntryPromptDialog entryPromptDialog = new EntryPromptDialog(mContext,EntryPromptDialog.mStringEntry,"");
                    entryPromptDialog.show();
                    e.printStackTrace();
                }
            }

            @Override public void onFailure(Throwable error) {
                mLogger.info("判断网络是否可用--->结果是———不可用");
                    //应该是在验证上网成功后保存
                mUploadDialog.dismiss();
                EntryPromptDialog entryPromptDialog = new EntryPromptDialog(mContext,EntryPromptDialog.mStringEntry,"");
                entryPromptDialog.show();
            }
        });
    }

}

